package com.mccree.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);

        String message = new String(bytes, StandardCharsets.UTF_8);

        System.out.println("服务器接收到的数据:"+message);
        System.out.println("服务器接收到的消息量:"+(++this.count));

        //服务器给客户端回送一个随机的id
        ByteBuf copiedBuffer = Unpooled.copiedBuffer(UUID.randomUUID().toString() + "\t", StandardCharsets.UTF_8);
        ctx.writeAndFlush(copiedBuffer);
    }
}
